#!/usr/bin/perl
#save_global.cgi

require './globalnet-lib.pl';

&ReadParse();
&error_setup($text{'global_config_error'});
if ($in{'gatewayin'})
{
	my $bonding = "off";
        local (@lref,$line);
        open(LSMOD, "lsmod |");
        while(<LSMOD>) {
                s/\r|\n//g;
                if (/^\S+/) { push(@lref, $_); }
                else { $lref[$#lref] .= $_; }
        }
        close(LSMOD);

        foreach $line (@lref)
        {
                if($line=~/bonding/)
                {
                        $bonding = "on";
                        last;
                }
        }

	&check_ipaddress($in{'gatewayin'}) || (&nas_syslog("globalnet", "naslog_warning", 17001, "Invalid gateway format"), &error(&text('gateway_ens', $in{'gatewayin'})));
	my $gatewayfile = ($bonding eq "on")?"/etc/sysconfig/network-scripts/ifcfg-bond0":"/etc/sysconfig/network-scripts/ifcfg-eth0";
	&lock_file($gatewayfile);
	&read_env_file($gatewayfile, \%conf);
	$conf{'GATEWAY'} = $in{'gatewayin'};
	&write_env_file($gatewayfile, \%conf);
	&unlock_file($gatewayfile);
	if($bonding eq "on")
	{
		`route del default`;
		`ifup bond0`;
	}
	else
	{
		`route del default dev eth0`;
                `route del default dev eth1`;
		`ifup eth0`;
	}
	`/etc/init.d/network reload`;
}
&save_gw2();
if($in{'gw2'} ne ""){
   system("route add default gw ".$in{'gw2'});
#  system("/root/a");
}
$dns = { };
@dnslist = split(":", $in{'dnscache'});
for($i=0; $i<@dnslist; $i++) {
	$dnslist[$i] =~ s/^\s+//;
	$dnslist[$i] =~ s/\s+$//;
	if ($dnslist[$i]) {
		&check_ipaddress($dnslist[$i]) ||(&nas_syslog("globalnet", "naslog_warning", 17002, "Invalid dns format"), 
			&error(&text('dns_ens', $dnslist[$i])));
		push(@{$dns->{'nameserver'}}, $dnslist[$i]);
	}
}

@domainlist = split(":", $in{'domaincache'});

foreach $d (@domainlist) {
	$d =~ /^[A-z0-9\.\-]+$/ ||(&nas_syslog("globalnet", "naslog_warning", 17003, "Invalid domain format"),
			&error(&text('dns_edomain', $d)));
	push(@{$dns->{'domain'}}, $d);
}

@hostslist = split(":", $in{'hostscache'});
foreach $d (@hostslist) {
	$d =~ /^(.*)=(.*)$/;
	$ip=$1;
	&check_ipaddress($ip) || (&nas_syslog("globalnet", "naslog_warning", 17004, "Invalid IP address"), &error(&text('ip_ens', $ip)));
}

#&lock_file($config{'network_config'});
#&read_env_file($config{'network_config'}, \%conf);
#$conf{'GATEWAY'} = $in{'gatewayin'};
#&write_env_file($config{'network_config'}, \%conf);
#&unlock_file($config{'network_config'});

&save_dns_config($dns);

&save_hosts(\@hostslist);
&nas_syslog("globalnet", "naslog_info", 17005, "Change global network settings success!");
&redirect("");


